<template>
  <s-layout>
    <view class="container">
      <view class="form-container">
        <!-- 头部标题 -->
        <view class="header-box" v-if="formData.id && !zhenggai">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">修改消防隐患排查</text>
        </view>

        <view class="header-box" v-if="zhenggai">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">整改记录</text>
        </view>

        <view class="header-box" v-if="!formData.id && !zhenggai">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">新增消防隐患排查</text>
        </view>

        <view v-if="!zhenggai">
          <!-- 基本信息区块 -->
          <view class="form-card">
            <fui-section
              title="基本信息"
              line-width="3px"
              line-color="#0052d9"
              isLine
              size="34"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                margin-bottom: 30rpx;
              "
            >
            </fui-section>

            <!-- 培训标题 -->
            <view class="form-item">
              <text
                class="cicon-title"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">隐患标题:</text>
              <fui-input
                placeholder="请输入隐患排查标题"
                v-model="formData.title"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
              >
              </fui-input>
            </view>

            <!-- 检查时间日期 -->
            <view class="form-item" @click="showDatePicker = true">
              <text
                class="cicon-time"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">检查时间:</text>
              <fui-input
                placeholder="请输入检查时间"
                v-model="formData.time"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
				disabled
              >
              </fui-input>
              <fui-date-picker
                :show="showDatePicker"
                type="3"
                @change="confirmDate"
              >
              </fui-date-picker>
            </view>

            <!-- 检查地点 SAIL输入框-->
            <view class="form-item">
              <text
                class="cicon-location-on"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">检查地点:</text>
              <fui-input
                placeholder="请输入检查地点"
                v-model="formData.address"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
              >
              </fui-input>
            </view>
          </view>

          <!-- 演练详情区块 -->
          <view class="form-card">
            <fui-section
              title="隐患详情"
              line-width="3px"
              line-color="#0052d9"
              isLine
              size="34"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                margin-bottom: 30rpx;
              "
            >
            </fui-section>

            <!-- 检查地点 SAIL输入框-->
            <view class="form-item">
              <text
                class="cicon-person"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">检查情况:</text>
              <fui-input
                placeholder="请输入检查情况"
                v-model="formData.situtation"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
              >
              </fui-input>
            </view>

            <!-- 检查地点 SAIL输入框-->
            <view class="form-item">
              <text
                class="cicon-person"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">检查人员:</text>
              <fui-input
                placeholder="请输入检查人员"
                v-model="formData.name"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
              >
              </fui-input>
            </view>

            <view class="form-item" @click="showTypePicker = true">
              <text
                class="cicon-tag"
                style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
              ></text>
              <text style="color: #4f4e4e">检查状态:</text>
              <fui-input
                placeholder="请选择检查状态"
                v-model="formData.status"
                :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
                :borderBottom="false"
				disabled
              >
              </fui-input>
              <fui-picker
                :show="showTypePicker"
                :options="typeOptions"
                @change="
                  (e) => {
                    formData.status = e.text;
                    formData.s_status = e.value;
                    showTypePicker = false;
                  }
                "
                linkage
                layer="1"
              >
              </fui-picker>
            </view>

            <text class="form-item-title">检查内容：</text>
            <!-- 培训内容 -->
            <view class="form-item">
              <fui-textarea
                v-model="formData.content"
                isCounter
                height="200"
                placeholder="请输入检查内容"
              ></fui-textarea>
            </view>
          </view>

          <!-- 多媒体区块 -->
          <view class="form-card">
            <fui-section
              title="隐患排查多媒体"
              line-width="3px"
              line-color="#0052d9"
              isLine
              size="34"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                margin-bottom: 30rpx;
              "
            >
            </fui-section>

            <!-- 使用s-upload组件替换原有的上传组件 -->
            <s-upload
              v-model="formData.files"
              title="上传附件"
              :initial-images="formData.image"
              :initial-videos="formData.video"
              :initial-files="formData.file"
              :max-image-count="maxImageCount"
              :max-file-count="maxFileCount"
              :max-video-count="maxVideoCount"
              :max-total-files="maxTotalFiles"
              :uploadUrl="upLoadrUrl"
            />
          </view>
        </view>
      </view>

      <!-- 整改记录 -->
      <view v-if="zhenggai">
        <view class="form-card">
          <fui-section
            title="整改记录"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              margin-bottom: 30rpx;
            "
          >
          </fui-section>

          <view class="form-item">
            <text
              class="cicon-evaluate"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">整该措施：</text>
            <fui-input
              placeholder="请输入检查整改措施"
              v-model="rectificationRecords.sr_measure"
              :padding="['0rpx', '20rpx', '0rpx', '0rpx']"
              :borderBottom="false"
            >
            </fui-input>
          </view>

          <view class="form-item">
            <text
              class="cicon-person"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">整改人员：</text>
            <fui-input
              placeholder="请输入整改人员"
              v-model="rectificationRecords.sr_people"
              size="28"
              :padding="['0rpx', '20rpx', '0rpx', '0rpx']"
              style="
                position: relative;
                --fui-picker-color: #1a1a1a;
              "
              :borderBottom="false"
            >
            </fui-input>
          </view>
          <view class="form-item" @click="showDatePicker = true">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">整改时间:</text>
            <fui-input
              placeholder="请输入整改时间"
              v-model="rectificationRecords.sr_time"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
			  disabled
            >
            </fui-input>
            <fui-date-picker
              :show="showDatePicker"
              type="3"
              @change="confirmDate"
            >
            </fui-date-picker>
          </view>
          <view class="form-item" @click="showTypePicker2 = true">
            <text
              class="cicon-tag"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">整改状态:</text>
            <fui-input
              placeholder="请输入整改情况"
              v-model="rectificationRecords.sr_status"
              :padding="['0rpx', '20rpx', '0rpx', '0rpx']"
              :borderBottom="false"
              disabled
            ></fui-input>
            <fui-picker
              :show="showTypePicker2"
              :options="typeOptions2"
              linkage
              layer="1"
              @change="
                (e) => {
                  rectificationRecords.sr_status = e.text;
                  rectificationRecords.status = e.value;
                  showTypePicker2 = false;
                }
              "
            >
            </fui-picker>
          </view>
        </view>
        <!-- 使用s-upload组件替换原有的上传组件 -->
        <view class="form-card">
          <fui-section
            title="整改附件"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              margin-bottom: 30rpx;
            "
          >
          </fui-section>

          <!-- 使用s-upload组件替换原有的上传组件 -->
          <s-upload
            v-model="rectificationRecords.file"
            :max-image-count="maxImageCount"
            :max-file-count="maxFileCount"
            :max-video-count="maxVideoCount"
            :max-total-files="maxTotalFiles"
            :uploadUrl="upLoadrUrl"
            :initial-images="rectificationRecords.sr_images"
            :initial-videos="rectificationRecords.sr_videos"
            :initial-files="rectificationRecords.sr_files"
          />
        </view>
      </view>
      <!-- 提交按钮 -->
      <view class="submit-btn" @click="handleSubmit">
        <text class="btn-text" v-if="!zhenggai">提交隐患排查</text>
        <text class="btn-text" v-if="zhenggai">提交整改记录</text>
      </view>
    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";
import SUpload from "@/sheep/components/s-upload/s-upload.vue";

const formData = ref({
  checkContent: "",
  videoUrl: [],
  checkSituation: "",
  time: "",
  tag: "",
  checkGroup: "",
  title: "",
  carouselImages: [],
  files: [], // 新增files字段用于s-upload组件
  image: [], // 保留原有字段以兼容旧代码
  video: [], // 保留原有字段以兼容旧代码
  file: [], // 保留原有字段以兼容旧代码
});

const rectificationRecords = ref({
  sr_measure: "",
  sr_people: "",
  sr_time: "",
  sr_status: "",
  sr_videos: "",
  sr_files: "",
  sr_images: "",
  images: [], // 保留原有字段以兼容旧代码
  videos: [], // 保留原有字段以兼容旧代码
  files: [], // 保留原有字段以兼容旧代码
  file: [], // 保留原有字段以兼容旧代码
});
// 选择器相关
const showDatePicker = ref(false);
const showTypePicker = ref(false);
const typeOptions = ref([
  {
    text: "治理中",
    value: "1",
  },
  {
    text: "治理完成",
    value: "2",
  },
  {
    text: "无隐患",
    value: "3",
  },
]);

const showTypePicker2 = ref(false);
const typeOptions2 = ref([
  {
    text: "全部整理",
    value: "1",
  },
  {
    text: "部分整理",
    value: "2",
  },
]);

const maxImageCount = ref(3); // 最大图片数量
const maxFileCount = ref(3); // 最大文件数量
const maxVideoCount = ref(3); // 最大视频数量
const maxTotalFiles = ref(9); // 最大附件总数量

const confirmDate = (e: any) => {
  formData.value.time = e.result;
  rectificationRecords.value.sr_time = e.result;
  showDatePicker.value = false;
};

const upLoadrUrl =
  "/app_api.php?t=upload&op=image_upload&role=company&type=danger";

// 移除旧的上传相关代码，使用s-upload组件的事件处理



const zhenggai = ref(false);

//获取页面数据
onLoad((options) => {
  

  if (options.id) {
    zhenggai.value = options.zhenggai == "true";
    formData.value.id = options.id;
    const params = {
      s_id: options.id,
      company_id: sheep.$store("user").userInfo.company_id,
    };
    sheep.$api.qy_hiddendanger.detail(params).then((res) => {
      formData.value = res.data?.screen_info;
      // SAIL bug  rectificationRecords.value = res.data.screen_records?.[0]是数组形式
      rectificationRecords.value = res.data.screen_records[0]
        ? res.data.screen_records[0]
        : {};

      console.log("rectificationRecords", rectificationRecords.value);
    });
  } else {
    formData.value = {};
  }
});
// 不再需要获取旧上传组件的引用

// 表单验证函数
const validateForm = () => {
  if (zhenggai.value) {
    // 整改记录验证
    if (!rectificationRecords.value.sr_measure) {
      uni.showToast({ title: "请填写整改措施", icon: "none" });
      return false;
    }
    if (!rectificationRecords.value.sr_people) {
      uni.showToast({ title: "请填写整改人员", icon: "none" });
      return false;
    }
    if (!rectificationRecords.value.sr_time) {
      uni.showToast({ title: "请选择整改时间", icon: "none" });
      return false;
    }
    if (!rectificationRecords.value.status) {
      uni.showToast({ title: "请选择整改状态", icon: "none" });
      return false;
    }
  } else {
    // 隐患排查验证
    if (!formData.value.title) {
      uni.showToast({ title: "请填写隐患标题", icon: "none" });
      return false;
    }
    if (!formData.value.time) {
      uni.showToast({ title: "请选择检查时间", icon: "none" });
      return false;
    }
    if (!formData.value.address) {
      uni.showToast({ title: "请填写检查地点", icon: "none" });
      return false;
    }
    if (!formData.value.situtation) {
      uni.showToast({ title: "请填写检查情况", icon: "none" });
      return false;
    }
    if (!formData.value.name) {
      uni.showToast({ title: "请填写检查人员", icon: "none" });
      return false;
    }
    if (!formData.value.s_status && !formData.value.status) {
      uni.showToast({ title: "请选择检查状态", icon: "none" });
      return false;
    }
    if (!formData.value.content) {
      uni.showToast({ title: "请填写检查内容", icon: "none" });
      return false;
    }
  }
  return true;
};

// 表单提交
const handleSubmit = () => {
  console.log("formData.value", formData.value);
  
  // 表单验证
  if (!validateForm()) return;
  
  if (zhenggai.value) {
    // 将文件按类型分类
    const images = [];
    const videos = [];
    const docFiles = [];

    rectificationRecords.value.file?.forEach((file) => {
      if (file.fileType === "image") {
        images.push(file.filePath);
      } else if (file.fileType === "video") {
        videos.push(file.filePath);
      } else if (file.fileType === "file") {
        docFiles.push(file.filePath);
      }
    });
    const data = {
      s_id: formData.value.id,
      sr_measure: rectificationRecords.value.sr_measure,
      sr_people: rectificationRecords.value.sr_people,
      sr_time: rectificationRecords.value.sr_time,
      sr_status: rectificationRecords.value.status,
      sr_videos: videos,
      sr_files: docFiles,
      sr_images: images,
    };
    uni.showLoading({ title: "提交中...", mask: true });
    sheep.$api.qy_hiddendanger.updateRecord(data).then((res) => {
      console.log("提交中...", res);
    });
  } else {
    // 将文件按类型分类
    const images = [];
    const videos = [];
    const docFiles = [];

    formData.value.files?.forEach((file) => {
      if (file.fileType === "image") {
        images.push(file.filePath);
      } else if (file.fileType === "video") {
        videos.push(file.filePath);
      } else if (file.fileType === "file") {
        docFiles.push(file.filePath);
      }
    });
    const data = {
      s_id: formData.value.id,
      company_id: sheep.$store("user").userInfo.company_id,
      s_address: formData.value.address,
      s_content: formData.value.content,
      s_name: formData.value.name,
      s_phone: formData.value.phone,
      s_situtation: formData.value.situtation,
      s_status: formData.value.s_status,
      s_time: formData.value.time,
      s_title: formData.value.title,
      s_image: images,
      s_video: videos,
      s_file: docFiles,
    };

    uni.showLoading({ title: "提交中...", mask: true });
    sheep.$api.qy_hiddendanger.update(data).then((res) => {
      console.log("提交中...", res);
    });
  }

  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({ title: "提交成功", icon: "success" });

    // 发送数据更新事件，通知其他页面刷新数据
    uni.$emit("hiddendangerDataUpdated", {
      timestamp: Date.now(),
      action: zhenggai.value ? "rectify" : "update",
      moduleType: "hiddendanger",
    });

    // 使用uni.navigateBack替代sheep.$router.go，更好地支持事件系统
    setTimeout(() => uni.navigateBack());
  }, 1500);
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background: #f8f9fa;
  min-height: 100vh;
}

.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
}

.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  font-size: 32rpx;
  border-bottom: 1rpx solid #eee;
}

.form-item-title {
  display: flex;
  align-items: center;
  padding-top: 20rpx;
  padding-left: 32rpx;
  font-size: 32rpx;
}

.upload-item {
  margin-top: 30rpx;
  .upload-box {
    height: 200rpx;
    background: #ecf5ff;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
  }
}

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
  .btn-text {
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
  }
}
</style>
